extends Node2D
@onready var card_1_his: Card = $HistoryContainer/HBoxContainer/HBoxContainer/Card1
@onready var card_2_his: Card = $HistoryContainer/HBoxContainer/HBoxContainer/Card2
@onready var card_3_his: Card = $HistoryContainer/HBoxContainer/HBoxContainer/Card3
@onready var card_4_his: Card = $HistoryContainer/HBoxContainer/HBoxContainer/Card4
@onready var card_result_his: Card = $HistoryContainer/HBoxContainer/HBoxContainer2/CardResult
@onready var card_1: Card = $HistoryContainer2/HBoxContainer/HBoxContainer/Card1
@onready var card_2: Card = $HistoryContainer2/HBoxContainer/HBoxContainer/Card2
@onready var card_3: Card = $HistoryContainer2/HBoxContainer/HBoxContainer/Card3
@onready var card_4: Card = $HistoryContainer2/HBoxContainer/HBoxContainer/Card4
@onready var easy_mode: Button = $HBoxContainer/EasyMode
@onready var hard_mode: Button = $HBoxContainer/HardMode
@onready var suit_option: OptionButton = $HistoryContainer2/HBoxContainer/AnswerContainer/HBoxContainer/SuitOption
@onready var num_option: OptionButton = $HistoryContainer2/HBoxContainer/AnswerContainer/HBoxContainer/NumOption
const COLOR_OVERLAY: PackedScene      = preload("res://core/components/color_overlay.tscn")
var card_list: Array[int]             = []
var card_list_his: Array[int]         = []
var num_answer: int                   = 0
var card_answer: String               = ''
var last_mode: String                 = 'easy'


func _ready() -> void:
	_show_puzzle_info()
	_restart_easy_game()


func _on_puzzle_info_pressed() -> void:
	_show_puzzle_info()


func _show_puzzle_info() -> void:
	var overlay: ColorOverlay = COLOR_OVERLAY.instantiate()

	add_child(overlay)

	overlay.set_title(tr("cg.card_guess_puzzle"))
	overlay.set_label(tr("cg.card_guess_puzzle_info"))
	var confirm_button: Button = Button.new()
	confirm_button.text = tr("m.confirm")
	confirm_button.connect("pressed", overlay.queue_free)

	overlay.operation_container.add_child(confirm_button)


func _generate_random_cards() -> Array[int]:
	var tmp_list: Array[int] = []

	while tmp_list.size() < 5:
		var random_number: int = randi_range(1, 52)
		if random_number in tmp_list:
			continue
		tmp_list.append(random_number)
	tmp_list.sort()
	return tmp_list


func _get_random_cards() -> void:
	card_list = _generate_random_cards()


func _get_random_cards_his() -> void:
	card_list_his = _generate_random_cards()


func _get_card_info_easy(p_card_list: Array[int]) -> Dictionary:
	var mod_list: Array[int] = []
	var num_list: Array[int] = []
	for i in p_card_list:
		mod_list.append(i % 4)
		num_list.append((i + 3) >> 2)

	var i: int = -1
	var j: int = -1
	for x in range(mod_list.size()):
		for y in range(x + 1, mod_list.size()):
			if mod_list[x] == mod_list[y]:
				i = x
				j = y
				break

	var first_num: int   = 0
	var selected: int    = -1
	var diff: int        = abs(num_list[j] - num_list[i])
	var diff_result: int = 0

	if diff <= 6:
		selected = j
		diff_result = diff
		first_num = p_card_list[i]
	else:
		selected = i
		diff_result = 13 - diff
		first_num = p_card_list[j]

	var selected_num: int = p_card_list[selected]
	var nums_left: Array  = []
	for x in range(p_card_list.size()):
		if x != i and x != j:
			nums_left.append(p_card_list[x])

	# 对nums_left进行排序
	nums_left.sort()

	# 定义排列模式，索引对应diff_result-1
	var patterns: Array[Array] = [
									 [0, 1, 2], # 1: 小中大
									 [0, 2, 1], # 2: 小大中
									 [1, 0, 2], # 3: 中小大
									 [1, 2, 0], # 4: 中大小
									 [2, 0, 1], # 5: 大小中
									 [2, 1, 0]  # 6: 大中小
								 ]

	# 根据diff_result选择对应的排列模式
	var pattern_index: int = diff_result - 1
	var pattern: Array     = patterns[pattern_index]
	var reordered: Array   = []
	for index in pattern:
		reordered.append(nums_left[index])
	nums_left = reordered

	return {
		"first_num": first_num,
		"selected_num": selected_num,
		"nums_left": nums_left
	}


func _get_card_info_hard(p_card_list: Array[int]) -> Dictionary:
	var num_sum: int = 0
	for num in p_card_list:
		num_sum += num
	var mod: int = (num_sum % 5) - 1
	if mod == -1:
		mod = 4
	var selected_num: int        = p_card_list[mod]
	var nums_left: Array = []
	for num in p_card_list:
		if num != selected_num:
			nums_left.append(num)

	# 生成0,1,2,3的所有排列
	var patterns: Array[Array] = [
										 [0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1],
										 [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0],
										 [2, 0, 1, 3], [2, 0, 3, 1], [2, 1, 0, 3], [2, 1, 3, 0], [2, 3, 0, 1], [2, 3, 1, 0],
										 [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]
									 ]

	# 每5个数字为1组, 52个数字共11组, 确定selected的分组
	var pattern_index: int = floori((selected_num + 4) / 5.0) - 1
	var pattern: Array = patterns[pattern_index]
	var reordered: Array   = []
	for index in pattern:
		reordered.append(nums_left[index])
	nums_left = reordered
	return {
		"nums_left": nums_left,
		"selected_num": selected_num
	}
	
func _sort_random_cards_hard() -> void:
	var card_info: Dictionary = _get_card_info_hard(card_list)
	card_1.set_suit(card_info.nums_left[0] % 4)
	card_1.set_label((card_info.nums_left[0] + 3) >> 2)
	card_2.set_suit(card_info.nums_left[1] % 4)
	card_2.set_label((card_info.nums_left[1] + 3) >> 2)
	card_3.set_suit(card_info.nums_left[2] % 4)
	card_3.set_label((card_info.nums_left[2] + 3) >> 2)
	card_4.set_suit(card_info.nums_left[3] % 4)
	card_4.set_label((card_info.nums_left[3] + 3) >> 2)
	num_answer = card_info.selected_num
	var _suits_list: Array[String] = ["♠", "♦", "♣", "♥"]
	var _nums_list: Array[String]  = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
	card_answer = _suits_list[card_info.selected_num % 4] + _nums_list[((num_answer + 3) >> 2) - 1]
	
func _sort_random_cards_hard_his() -> void:
	var card_info: Dictionary = _get_card_info_hard(card_list_his)
	card_1_his.set_suit(card_info.nums_left[0] % 4)
	card_1_his.set_label((card_info.nums_left[0] + 3) >> 2)
	card_2_his.set_suit(card_info.nums_left[1] % 4)
	card_2_his.set_label((card_info.nums_left[1] + 3) >> 2)
	card_3_his.set_suit(card_info.nums_left[2] % 4)
	card_3_his.set_label((card_info.nums_left[2] + 3) >> 2)
	card_4_his.set_suit(card_info.nums_left[3] % 4)
	card_4_his.set_label((card_info.nums_left[3] + 3) >> 2)
	card_result_his.set_suit(card_info.selected_num % 4)
	card_result_his.set_label((card_info.selected_num + 3) >> 2)


# 简化后的方法
func _sort_random_cards_easy() -> void:
	var card_info: Dictionary = _get_card_info_easy(card_list)

	card_1.set_suit(card_info.first_num % 4)
	card_1.set_label((card_info.first_num + 3) >> 2)
	card_2.set_suit(card_info.nums_left[0] % 4)
	card_2.set_label((card_info.nums_left[0] + 3) >> 2)
	card_3.set_suit(card_info.nums_left[1] % 4)
	card_3.set_label((card_info.nums_left[1] + 3) >> 2)
	card_4.set_suit(card_info.nums_left[2] % 4)
	card_4.set_label((card_info.nums_left[2] + 3) >> 2)
	num_answer = card_info.selected_num
	var _suits_list: Array[String] = ["♠", "♦", "♣", "♥"]
	var _nums_list: Array[String]  = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
	card_answer = _suits_list[card_info.selected_num % 4] + _nums_list[((num_answer + 3) >> 2) - 1]


func _sort_random_cards_easy_his() -> void:
	var card_info: Dictionary = _get_card_info_easy(card_list_his)

	card_1_his.set_suit(card_info.first_num % 4)
	card_1_his.set_label((card_info.first_num + 3) >> 2)
	card_2_his.set_suit(card_info.nums_left[0] % 4)
	card_2_his.set_label((card_info.nums_left[0] + 3) >> 2)
	card_3_his.set_suit(card_info.nums_left[1] % 4)
	card_3_his.set_label((card_info.nums_left[1] + 3) >> 2)
	card_4_his.set_suit(card_info.nums_left[2] % 4)
	card_4_his.set_label((card_info.nums_left[2] + 3) >> 2)
	card_result_his.set_suit(card_info.selected_num % 4)
	card_result_his.set_label((card_info.selected_num + 3) >> 2)


func _on_next_group_pressed() -> void:
	_get_random_cards_his()
	if last_mode == "easy":
		_sort_random_cards_easy_his()
	else:
		_sort_random_cards_hard_his()

func _on_hard_mode_pressed() -> void:
	if not last_mode == "hard":
		_restart_hard_game()
	last_mode = "hard"


func _on_easy_mode_pressed() -> void:
	if not last_mode == "easy":
		_restart_easy_game()
	last_mode = "easy"


func _restart_easy_game() -> void:
	_get_random_cards()
	_get_random_cards_his()
	_sort_random_cards_easy()
	_sort_random_cards_easy_his()
	
func _restart_hard_game() -> void:
	_get_random_cards()
	_get_random_cards_his()
	_sort_random_cards_hard()
	_sort_random_cards_hard_his()


func _on_restart_game_pressed() -> void:
	_restart_game()


func _restart_game() -> void:
	if last_mode == "easy":
		_restart_easy_game()
	else:
		_restart_hard_game()


func _on_confrim_pressed() -> void:
	var _mod: int    = suit_option.selected
	var _num: int    = num_option.selected + 1
	var _answer: int = _num * 4 - _mod
	if _answer == num_answer:
		_puzzle_solved()
	else:
		_wrong_answer()


func _puzzle_solved() -> void:
	GameManager.set_puzzle_solved(true, "card_guess")
	GameManager.save_game()

	# 创建遮罩层
	var overlay: ColorOverlay = COLOR_OVERLAY.instantiate()
	add_child(overlay)

	overlay.set_title(tr("m.congratulations"))
	overlay.set_label(tr("m.solved"))

	# 创建返回主菜单按钮
	var menu_button = Button.new()
	menu_button.text = tr("m.back_to_menu")
	menu_button.size = Vector2(120, 40)


	# 连接按钮点击事件
	menu_button.connect("pressed", func():
		overlay.queue_free()  # 移除遮罩层
		GameManager.back_to_main_menu()  # 返回主菜单
	)


	overlay.operation_container.add_child(menu_button)


func _wrong_answer() -> void:
	# 创建遮罩层
	var overlay: ColorOverlay = COLOR_OVERLAY.instantiate()
	add_child(overlay)

	overlay.set_title(tr("m.wrong"))

	overlay.set_label(tr("cg.correct_answer_is") % card_answer)

	# 创建确认按钮
	var confirm_button = Button.new()
	confirm_button.text = tr("m.restart")

	confirm_button.position = Vector2(250, 140)
	confirm_button.size = Vector2(100, 40)

	# 连接按钮点击事件
	confirm_button.connect("pressed", func():
		overlay.queue_free()  # 移除遮罩层
		_restart_game()        # 重启游戏
	)
	overlay.operation_container.add_child(confirm_button)


func _on_back_to_menu_pressed() -> void:
	GameManager.back_to_main_menu()
